/* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2009 University of Washington
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <vector>
#include "ns3/log.h"
#include "ns3/ptr.h"
#include "ns3/names.h"
#include "ns3/node.h"
#include "ns3/ipv4.h"
#include "ns3/ipv4-route.h"
#include "ns3/ipv4-list-routing.h"
#include "ns3/assert.h"
#include "ns3/config.h"
#include "ns3/ipv4-address.h"
#include "ns3/ipv4-routing-protocol.h"
#include "ns3/point-to-point-net-device.h"
#include "ns3/queue.h"
#include "ns3/ppp-header.h"

#include "ipv4-texcp-routing-helper.h"

NS_LOG_COMPONENT_DEFINE("Ipv4TexcpRoutingHelper");

namespace ns3 {
namespace texcp_routing {
Ipv4TexcpRoutingHelper::Ipv4TexcpRoutingHelper()
{
 //std::cout<<"Helper1";
 m_agentFactory.SetTypeId("ns3::texcp_routing::Ipv4TexcpRouting");
 //std::cout<<"Helper2";
}


Ipv4TexcpRoutingHelper::Ipv4TexcpRoutingHelper (const Ipv4TexcpRoutingHelper &o)
  : m_agentFactory (o.m_agentFactory)
{
}

Ipv4TexcpRoutingHelper* 
Ipv4TexcpRoutingHelper::Copy (void) const 
{
  return new Ipv4TexcpRoutingHelper (*this); 
}

Ptr<Ipv4RoutingProtocol> 
Ipv4TexcpRoutingHelper::Create (Ptr<Node> node) const
{
  return m_agentFactory.Create<Ipv4TexcpRouting> ();
  //return CreateObject<Ipv4TexcpRouting> ();
}


Ptr<Ipv4TexcpRouting>
Ipv4TexcpRoutingHelper::GetTexcpRouting (Ptr<Ipv4> ipv4) const
{
  NS_LOG_FUNCTION (this);
  Ptr<Ipv4RoutingProtocol> ipv4rp = ipv4->GetRoutingProtocol ();
  NS_ASSERT_MSG (ipv4rp, "No routing protocol associated with Ipv4");
  if (DynamicCast<Ipv4TexcpRouting> (ipv4rp))
    {
      NS_LOG_LOGIC ("Texcp routing found as the main IPv4 routing protocol.");
      return DynamicCast<Ipv4TexcpRouting> (ipv4rp); 
    } 
  if (DynamicCast<Ipv4ListRouting> (ipv4rp))
    {
      Ptr<Ipv4ListRouting> lrp = DynamicCast<Ipv4ListRouting> (ipv4rp);
      int16_t priority;
      for (uint32_t i = 0; i < lrp->GetNRoutingProtocols ();  i++)
        {
          NS_LOG_LOGIC ("Searching for texcp routing in list");
          Ptr<Ipv4RoutingProtocol> temp = lrp->GetRoutingProtocol (i, priority);
          if (DynamicCast<Ipv4TexcpRouting> (temp))
            {
              NS_LOG_LOGIC ("Found texcp routing in list");
              return DynamicCast<Ipv4TexcpRouting> (temp);
            }
        }
    }
  NS_LOG_LOGIC ("Texcp routing not found");
  return 0;
}

void
Ipv4TexcpRoutingHelper::EnableAscii (std::string prefix, NodeContainer n)
{
  NS_LOG_FUNCTION(this);
  for (NodeContainer::Iterator i = n.Begin (); i != n.End (); ++i)
  {
    Ptr<Node> node = *i;
    EnableAsciiInternal (prefix, node);
  }
}

void 
Ipv4TexcpRoutingHelper::EnableAsciiInternal (std::string prefix, Ptr<Node> nd)
{
  NS_LOG_FUNCTION(this);
  Ptr<Ipv4> ipv4 = nd->GetObject<Ipv4>();
  Ptr<Ipv4TexcpRouting> routingProtocol = GetTexcpRouting (ipv4);

  std::string newPrefix, filename;


  AsciiTraceHelper asciiTraceHelper;
  // log stats (loss calculations, fwnd)
  if(routingProtocol)
  {
    std::string newPrefix = prefix+"-stat";
    std::string filename = asciiTraceHelper.GetFilenameFromNode (newPrefix, nd);

    Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream (filename);
    routingProtocol->TraceConnectWithoutContext("UpdateWeight", MakeBoundCallback (&Ipv4TexcpRoutingHelper::DefaultUpdateFwnd,stream));
  }

  newPrefix = prefix+"-out";
  filename = asciiTraceHelper.GetFilenameFromNode (newPrefix, nd);

  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream (filename);
  ipv4->TraceConnectWithoutContext("UnicastForward", MakeBoundCallback (&Ipv4TexcpRoutingHelper::TexcpForward,stream));
}

/*void
Ipv4TexcpRoutingHelper::EnableAscii (std::string prefix, NodeContainer n)
{
  NS_LOG_FUNCTION(this);
  EnableAsciiImpl (Ptr<OutputStreamWrapper> (), prefix, n);
}

void
Ipv4TexcpRoutingHelper::EnableAsciiImpl (Ptr<OutputStreamWrapper> stream, std::string prefix, NodeContainer n)
{
  NS_LOG_FUNCTION(this);
  for (NodeContainer::Iterator i = n.Begin (); i != n.End (); ++i)
  {
      Ptr<Node> node = *i;
      EnableAsciiInternal (stream, prefix, node, false);
  }
}

void 
Ipv4TexcpRoutingHelper::EnableAsciiInternal (Ptr<OutputStreamWrapper> stream, std::string prefix, Ptr<Node> nd, bool explicitFilename)
{
  NS_LOG_FUNCTION(this);
  Ptr<Ipv4> ipv4 = nd->GetObject<Ipv4>();
  
  Ptr<Ipv4TexcpRouting> routingProtocol = GetTexcpRouting (ipv4);

  if(routingProtocol == 0)
  {
      NS_LOG_INFO ("Ipv4TexcpRoutingHelper::EnableAsciiInternal(): Node " << nd << " not of TexcpRouting");
      return;
  }

  //
  // If we are not provided an OutputStreamWrapper, we are expected to create 
  // one using the usual trace filename conventions and do a Hook*WithoutContext
  // since there will be one file per context and therefore the context would
  // be redundant.
  //
  if (stream == 0)
    {
      //
      // Set up an output stream object to deal with private ofstream copy 
      // constructor and lifetime issues.  Let the helper decide the actual
      // name of the file given the prefix.
      //
      AsciiTraceHelper asciiTraceHelper;

      std::string filename;
      if (explicitFilename)
        {
          filename = prefix;
        }
      else
        {
          filename = asciiTraceHelper.GetFilenameFromNode (prefix, nd);
        }

      stream = asciiTraceHelper.CreateFileStream (filename);
    }

  routingProtocol->TraceConnectWithoutContext("UpdateWeight", MakeBoundCallback (&Ipv4TexcpRoutingHelper::DefaultUpdateFwnd,stream));
}*/

void
Ipv4TexcpRoutingHelper::TraceQueue (std::string prefix, NodeContainer n)
{
  NS_LOG_FUNCTION(this);
  for (NodeContainer::Iterator i = n.Begin (); i != n.End (); ++i)
  {
    Ptr<Node> node = *i;
    TraceQueueInternal (prefix, node);
  }
}


void 
Ipv4TexcpRoutingHelper::TraceQueueInternal (std::string prefix, Ptr<Node> nd)
{
  NS_LOG_FUNCTION(this);
  
  for (uint32_t i = 2; i < nd->GetNDevices (); i++)
    {
       Ptr<PointToPointNetDevice> ppnd = DynamicCast<PointToPointNetDevice>(nd->GetDevice(i));
       Ptr<Queue> qnd = ppnd->GetQueue();

       std::string newPrefix, filename;


        AsciiTraceHelper asciiTraceHelper;
        // log stats (loss calculations, fwnd)

        /*newPrefix = prefix+"-drop";
        filename = asciiTraceHelper.GetFilenameFromInterfacePair (newPrefix, nd, i);

        Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream (filename);
        qnd->TraceConnectWithoutContext("Drop", MakeBoundCallback (&Ipv4TexcpRoutingHelper::QueueDrop,stream));*/
        
       //New Tracing mechanism 
       Ptr<TexcpQueue> texcp_queue = DynamicCast<TexcpQueue> (qnd);

       newPrefix = prefix+"-dropping";
       filename = asciiTraceHelper.GetFilenameFromInterfacePair (newPrefix, nd, i);
       Ptr<OutputStreamWrapper> stream2 = asciiTraceHelper.CreateFileStream (filename);

       newPrefix = prefix+"-utilization";
       filename = asciiTraceHelper.GetFilenameFromInterfacePair (newPrefix, nd, i);
       Ptr<OutputStreamWrapper> stream3 = asciiTraceHelper.CreateFileStream (filename);


       if (texcp_queue)
         {
           texcp_queue-> TraceConnectWithoutContext("LinkDroppingRate", MakeBoundCallback (&Ipv4TexcpRoutingHelper::QueueDroppingRate,stream2));
           texcp_queue-> TraceConnectWithoutContext("LinkUtilization", MakeBoundCallback (&Ipv4TexcpRoutingHelper::LinkUtilization,stream3));
         }
      }
}


void
Ipv4TexcpRoutingHelper::DefaultUpdateFwnd (Ptr<OutputStreamWrapper> stream, Ptr<Ipv4TexcpTableEntry> p)
{
  NS_LOG_FUNCTION (stream << p);
  *stream->GetStream () << " " << p->GetDestNetwork() << " " << p->GetInterface() << " " << Simulator::Now ().GetMilliSeconds () << " " << p->GetWeight() << " " << p->GetLoss() << " " << "1" << " " << p->GetToken() << std::endl;

 /*  *stream->GetStream () << " " << p->GetDestNetwork() << " " << p->GetInterface() << " " \
                  << Simulator::Now ().GetMilliSeconds () << " " << p->GetFwnd() << " " << p->GetLoss() << " " << p->GetTotalBytes() << " " << p->GetTotalLostBytes() << std::endl; */
}

void
Ipv4TexcpRoutingHelper::QueueDrop (Ptr<OutputStreamWrapper> stream, Ptr<const Packet> p)
{
  NS_LOG_FUNCTION (stream << p);

  Ipv4HeaderPathTag tag;
  uint32_t dscp = 0;
  bool found = p->PeekPacketTag(tag);

  if ( found ) {
    dscp = tag.GetPath();
  }

  *stream->GetStream() << dscp << " "  << Simulator::Now().GetTimeStep() << " " <<  p->GetSize() << '\n';
}

void
Ipv4TexcpRoutingHelper::QueueDroppingRate (Ptr<OutputStreamWrapper> stream, double oldValue, double newValue)
{
  
  *stream->GetStream() << Simulator::Now().GetTimeStep() << " " <<  newValue << '\n';
}

void
Ipv4TexcpRoutingHelper::LinkUtilization (Ptr<OutputStreamWrapper> stream, double oldValue, double newValue)
{
  
  *stream->GetStream() << Simulator::Now().GetTimeStep() << " " <<  newValue << '\n';
}

void
Ipv4TexcpRoutingHelper::TexcpForward (Ptr<OutputStreamWrapper> stream, const Ipv4Header &header, Ptr<const Packet> p, uint32_t interface)
{
  NS_LOG_FUNCTION (stream << p);

  uint32_t reflex = header.GetFlags() & Ipv4Header::RESERVED_BIT;
  reflex += header.GetTos(Ipv4Header::ECN_MASK);

  *stream->GetStream() << interface << " "  << Simulator::Now().GetTimeStep() << " " << reflex << " " <<  p->GetSize() << '\n';
}

void
Ipv4TexcpRoutingHelper::SetAttribute (std::string name, const AttributeValue &value)
{
  m_agentFactory.Set (name, value);
}
}}; // namespace ns3
